<?php


namespace app\home\controller;

use app\admin\model\Push;
use app\home\model\NewsCommunication;
use app\home\model\NewsCommunicationDetail;
use app\home\model\WechatUser;
use app\home\model\WechatUserTag;
use com\wechat\TPQYWechat;
use think\Config;
use think\Db;
use think\Log;
use think\Model;

/**
 * Class Documents
 * @package app\home\controller
 * 上级来文communication
 */
class Documents extends Base
{
    protected $userid;
    protected $permission;
    public function _initialize()
    {
        parent::_initialize();
        $this->anonymous();
        $this->jssdk();
        $this->userid = session('userId');
        $map = [
            'userid' => $this->userid,
            'tagid' => ['in',[1,2,3,5,6]]
        ];
        $user = WechatUserTag::where($map)->find();
        if($user) {
            if($user['tagid'] == 1) { //总经理
                $this->permission = 1;
            }else if($user['tagid'] == 2){ //副总
                $this->permission = 2;
            }else {
                $this->permission = 3; //科室长，无待分发
            }
        }else {
            $this->permission = 0; //无权限查看
        }
        $this->assign('permission',$this->permission);
    }
    /**
     *  上级文件首页
     */
    public function index () {
        $Model = new NewsCommunication();
        $length = input('length',0);
        $status = input('status');
        if(IS_POST) {
            $list = $Model->getList($this->permission,$this->userid,$status,$length);
            if($list) {
                return $this->success("加载成功","",$list);
            }else {
                return $this->error("加载失败");
            }
        }else {
            $list = [
                'list_1' => $Model->getList($this->permission,$this->userid,0,$length),
                'list_2' => $Model->getList($this->permission,$this->userid,1,$length),
                'list_3' => $Model->getList($this->permission,$this->userid,2,$length),
            ];
            $this->assign('list',json_encode($list));
            return $this->fetch();
        }
    }

    /**
     *  上级文件分发
        'user' => [
            0 => [
                'permission' => $user['tagid'],
                'userid' => $user['userid'],
                'communication_id' => $detail['communication_id'],
            ],
            1 => [...]
         ],
        'remarks' => 'post.remarks',
     */
    public function distribute () {
        $Model = new NewsCommunicationDetail();
        if(IS_POST) {
            //分发文件
            $data = input('post.');
            foreach ($data['user'] as $key => $user) {
                $user['communication_id'] = $data['communication_id'];
                if($user['permission'] == 2) {
                    $user['status'] = 0; //待分发
                }else {
                    $user['status'] = 1; //轮阅中
                }
                $push = $Model->create($user);
                if($push) {
                    $this->push($push); //推送
                }
            }
            //分发成功，更新对应的状态
            $map = [
                'permission' => $this->permission,
                'userid' => $this->userid,
                'communication_id' => $data['communication_id'],
                'status' => 0
            ];
            //更新值
            $update = [
                'remarks' => isset($data['remarks']) ? $data['remarks'] : "",
                'status' => 1,
                'update_time' => time(),
            ];
            $res = $Model->where($map)->update($update);
            if($res) {
                return $this->success("分发成功",Url('Documents/index'));
            }else {
                return $this->error("分发失败");
            }
        }else {
            $id = input('id');
            if($id) {
                $detail = $Model->get($id);
                $this->assign('detail',json_encode($detail));
            }else{
                return$this->error("未选择分发文件,请选择！",Url('Documents/index'));
            }
            $user = $this->getApprovalUser($this->permission,$id);
            $this->assign('user',json_encode($user));
            return $this->fetch();
        }
    }

    /**
     * 获取分发对象
     * @param $permission
     * @return false|\PDOStatement|string|\think\Collection|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getApprovalUser($permission,$id) {
        if($permission == 1) {
            $user = WechatUserTag::where(['tagid' => ['in',[2,5,6]]])->select();
            foreach ($user as $value) {
                $u = WechatUser::where(['userid' => $value['userid']])->find();
                if($value['tagid'] != 2) {
                    $value['tagid'] = 3;
                }
                $value['username'] = $u['name'];
            }
        }else if($permission == 2){
            $user = WechatUserTag::where(['tagid' => 3])->select();
            foreach ($user as $key => $value) {
                $u = WechatUser::where(['userid' => $value['userid']])->find();
                $value['username'] = $u['name'];
            }
        }else{
            return $this->error("暂无权限执行分发文件操作",Url('Documents/index'));
        }
        return $user;
    }


    /**
     *  上级文件详情 / 文件归档方法
     */
    public function detail () {
        $Model = new NewsCommunicationDetail();
        $id = input('id');
        $remarks = input('remarks');
        if(IS_POST) {
            //文件归档
            $data = [
                'status' => 2,
                'update_time' => time(),
                'remarks' => $remarks
            ];
            $res = $Model->where(['id' => $id])->update($data);
            if($res) {
                $info = $Model->where(['id' => $id])->find();
                if($this->permission == 2) { //副总结束归档
//                    $Model->where('communication_id',$info['communication_id'])->update(['status' => 2]);
                    return $this->success("结束归档成功",Url('Documents/detail',['id' => $info['id']]),$res);
                }else { //科室长归档完成改变归档状态
                    //查询是否存在未归档用户
                    $map1 = [
                        'communication_id' => $info['communication_id'],
                        'permission' => 3,
                        'status' => 1
                    ];
                    $info1 = $Model->where($map1)->find();
                    //全部归档则更新总经理、副总文件状态status1->2
                    if(empty($info1)) {
                        $map2 = [
                            'communication_id' => $info['communication_id'],
                            'permission' => ['in',[1,2]],
                            'status' => 1
                        ];
                        $Model->where($map2)->update(['status' => 2]);
                    }
                    return $this->success("归档成功",Url('Documents/detail',['id' => $info['id']]),$res);
                }
            }else {
                return $this->error("归档失败");
            }
        }else {
            $detail = $Model->getDetail($id,$this->permission);
            $this->assign('detail',json_encode($detail));

            return $this->fetch();
        }
    }

    /**
     * 推送
     */
    private function push($data){
        $communication = NewsCommunication::get(['id' => $data['communication_id']]);
        $type = [1 => "[行政]", 2 => "[党建]", 3 => "[工会]", 4 => "[其它]"];
        $type_text = $type[$communication['type']];
        if($data['permission'] < 3) {
            $title = "您有新的上级来文需要分发！";
        }else {
            $title = "您有新的上级来文需要归档！";
        }
        $send = [
            "title" => $title,
            'description' => "<div class=\"gray\">时间: ".date("Y-m-d H:i",time())."</div><div class=\"gray\">标题: ".$communication['title']."</div><div class=\"gray\">类型: ".$type_text."</div><div class=\"highlight\">点击查看</div>",
            "url" => $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'].'/home/documents/detail/id/'.$data['id'],
        ];
        //发送给服务号
        $Wechat = new TPQYWechat(Config::get('news'));
        $message = array(
            "touser" => 18768112486,
//            "touser" => $data['userid'],
            "msgtype" => 'textcard',
            "agentid" => config('news.agentid'),
            "textcard" => $send,
            "safe" => "0"
        );
        $data = [
            'type' => 1,
            'agentname' => "news",
            'touser' => $message['touser'],
            'msgtype' => $message['msgtype'],
            'agentid' => $message['agentid'],
            'sendcontent' => json_encode($message['textcard']),
            'safe' => $message['safe'],
        ];
        $res = Push::create($data);
        $msg = $Wechat->sendMessage($message);
        if ($msg['errcode'] == 0){
            Push::where('id',$res['id'])->update(['status' => 1,'update_time' => time()]);
            Log::write("上级来文消息发送：发送成功");
        }else{
            Log::write("上级来文消息发送：发送失败");
        }
        Log::write($msg);
    }
}
